package com.cicadasmall.system.wrapper;



import com.cicadasmall.common.constant.Constant;
import com.cicadasmall.common.enums.MenuType;
import com.cicadasmall.common.func.Fn;
import com.cicadasmall.common.utils.SpringContextUtils;
import com.cicadasmall.common.utils.TreeUtils;
import com.cicadasmall.common.utils.WarpsUtils;
import com.cicadasmall.common.wrapper.EntityWrapper;
import com.cicadasmall.data.domain.MenuDO;
import com.cicadasmall.system.vo.MenuVO;
import com.cicadasmall.system.vo.RouteVo;
import com.cicadasmall.data.mapper.SysMenuMapper;

import java.util.List;
import java.util.stream.Collectors;


public class MenuWrapper implements EntityWrapper<MenuDO, MenuVO> {

    private final static SysMenuMapper baseMapper;

    static {
        baseMapper = SpringContextUtils.getBean(SysMenuMapper.class);
    }

    public static MenuWrapper newBuilder() {
        return new MenuWrapper();
    }

    public RouteVo routeVO(MenuVO menuVo) {
        RouteVo routeVo = new RouteVo();
        routeVo.setName(menuVo.getMenuName());
        routeVo.setHidden(false);
        routeVo.setAlwaysShow(false);
        routeVo.setPath(menuVo.getMenuPath());
        routeVo.setComponent(menuVo.getComponent());
        RouteVo.Meta meta = new RouteVo.Meta();
        meta.setIcon(menuVo.getMenuIcon());
        meta.setTitle(menuVo.getMenuName());
        meta.setNoCache(true);
        if (menuVo.isHasChildren() && Fn.isNotEmpty(menuVo.getChildren())) {
            menuVo.getChildren().stream().forEach(sub -> {
                if (!Fn.equal(MenuType.按钮.getCode(), sub.getMenuType())) {
                    routeVo.getChildren().add(routeVO(sub));
                }
            });
        }
        routeVo.setMeta(meta);
        return routeVo;
    }

    public List<RouteVo> routeList(List<MenuVO> treeList) {
        return treeList.stream().map(this::routeVO).collect(Collectors.toList());
    }

    @Override
    public MenuVO entityVO(MenuDO entity) {
        MenuVO menuVo = WarpsUtils.copyTo(entity, MenuVO.class);
        if (Fn.isNotNull(menuVo.getParentId()) && Fn.notEqual(Constant.PARENT_ID, menuVo.getParentId())) {
            MenuDO parentMenu = baseMapper.selectById(menuVo.getParentId());
            menuVo.setParentName(parentMenu.getMenuName());
        } else {
            menuVo.setParentName("顶级类目");
        }
        return menuVo;
    }

    @Override
    public List<MenuVO> treeVO(List<MenuDO> list) {
        return TreeUtils.toTree(this.listVO(list));
    }

}
